<?php
/**
 * Created by PhpStorm.
 * User: lih
 * Date: 2018/4/19
 * Time: 23:54
 */

//上传附件
function uploadAttach()
{
    $ret = array();
    $ret['code'] = 0;
    $ret['msg'] = '';
    if(!$_FILES || false == isset($_FILES["fname"]))
    {
        $ret['code'] = 1;
        $ret['msg'] = "upFile is not set";
        return $ret;
    }

    $file = $_FILES["fname"];
    if (false == isset($file['tmp_name']) || false == is_file($file['tmp_name']))
    {
        $ret['code'] = 2;
        $ret['msg'] = "tmp_name is not file";
        return $ret;
    }
    if (0 == filesize($file['tmp_name']))
    {
        $ret['code'] = 3;
        $ret['msg'] = "tmp_name filesize is 0";
        return $ret;
    }

    $curlFile = new CurlFile($file['tmp_name'], $file['type'], $file['name']);
    $fileSuffix = getSuffix($curlFile->getPostFilename());

    $fileId = uploadToFastdfs($curlFile, $fileSuffix);
    if(empty($fileId)) {
        $ret['code'] = 4;
        $ret['msg'] = "upload failed";
        return $ret;
    }

    //$ret['file'] = $file;
    $ret['fileId'] = $fileId;
    return $ret;
}

//获取后缀
function getSuffix($fileName)
{
    preg_match('/\.(\w+)?$/', $fileName, $matchs);
    return isset($matchs[1])?$matchs[1]:'';
}

//上传文件到fastdfs
function uploadToFastdfs(CurlFile $file, $fileSuffix)
{
    $fdfs = new FastDFS();
    $tracker = $fdfs->tracker_get_connection();
    //$fileId = $fdfs->storage_upload_by_filebuff1(file_get_contents($file->getFilename()), $fileSuffix);
    $fileId = $fdfs->storage_upload_by_filename1($file->getFilename(), $fileSuffix);
    $fdfs->tracker_close_all_connections();
    return $fileId;
}

function startUpload()
{
    $ret = array();
    try {
        $ret = uploadAttach();
    } catch(\Exception $e) {
    }
    echo json_encode($ret);
}

startUpload();

?>